package com.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.demo.beans.ResultBean;
import com.demo.myexception.AopException;

@Aspect
@Component
@Order(5) // int value的值越小，优先级越高
public class ResultBeanAop {

	private static final Logger logger = LoggerFactory.getLogger(ResultBeanAop.class);

	// @Pointcut("@annotation(com.zktx.platform.log2.SystemControllerLog)")
	@Pointcut("execution(* com.demo.controller.*.*(..))")
	public void controllerAspect() {
	}

	@Around(value = "controllerAspect()")
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		ResultBean<?> result;
		try {
			result = (ResultBean<?>) pjp.proceed();
			logger.info(pjp.getSignature() + "  use time:" + (System.currentTimeMillis() - startTime));
		} catch (Throwable e) {
			result = handlerException(pjp, e);
		}
		return result;
	}

	private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		@SuppressWarnings("rawtypes")
		ResultBean<?> result = new ResultBean();
		// 已知异常
		if (e instanceof AopException) {
			result.setMsg(e.getLocalizedMessage());
			result.setCode(ResultBean.FAIL);
		} else {
			logger.error(pjp.getSignature() + " error ", e);
			result.setMsg(e.toString());
			result.setCode(ResultBean.FAIL);
			// 未知异常是应该重点关注的，这里可以做其他操作，如通知邮件，单独写到某个文件等等。
		}
		return result;
	}
}
